package action.FrontAction;

import com.alibaba.fastjson.JSON;
import com.opensymphony.xwork2.ActionSupport;
import common.StringUtils;
import entity.*;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import service.CroPurgoodsService;
import service.FrontGoodsDetailService;
import vo.*;

import javax.servlet.ServletContext;
import java.util.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

/**
 * Created by wsx on 2017/5/18.
 */
public class PurgoodsDeatilAction extends ActionSupport {
    private CroPurgoodsVo croPurgoodsVo;
    private List<CroPurgoodsVo> croPurgoodsVoList;
    private String goodsid;
    private String[] value;
    private String[] flag;
    private Double successResult;
    private Double goodsprice;
    private String goodsnumber;

    @Autowired
    private CroPurgoodsService croPurgoodsService;
    @Autowired
    private FrontGoodsDetailService frontGoodsDetailService;

    /*
     *获取商品详情页
      *  */
    public String getGoodsDetail() {
        System.out.println("getupdategoodsinfoaction" + goodsid);
        //
        croPurgoodsVo = croPurgoodsService.getUpdateGoodsInfo(goodsid);
        String json = croPurgoodsVo.getDescription();
        CroPurgoodsVos goods = new CroPurgoodsVos();
        goods = JSON.parseObject(json, CroPurgoodsVos.class);
        System.out.println("url:"+goods.getDescUrl());
        Map<String, Map> map = new HashMap<String, Map>();
        List<GoodsShowSkuItemsVo> goodsShowSkuItemsVoList = goods.getGoodsShowSkuItems();
        System.out.println("goodsShowSkuItemsVoList.size" + goodsShowSkuItemsVoList.size());
        for (GoodsShowSkuItemsVo goodsShowSkuItemsVo : goodsShowSkuItemsVoList) {
            Map tempmap = new HashMap();
            for (PropertyAliasListVo propertyAliasListVo : goodsShowSkuItemsVo.getPropertyAliasList()) {
                tempmap.put(propertyAliasListVo.getPropValueId(), propertyAliasListVo.getCustomName());
                System.out.println("值：" + propertyAliasListVo.getPropId());
            }
            System.out.println("map.size" + tempmap.size());
            map.put(goodsShowSkuItemsVo.getPropName(), tempmap);
        }
        croPurgoodsVo.setMaps(map);
        croPurgoodsVo.setImagurl(goods.getPicUrl());
        String html = null;
        if(StringUtils.isNotBlank(goods.getDescUrl())) {
            html = PurgoodsDeatilAction.getHtmlByURL(goods.getDescUrl());
            if (StringUtils.isNotBlank(html)) {
                html = html.substring(10, html.length() - 2);
            }
            if(StringUtils.isNotBlank(html)) {
                croPurgoodsVo.setHtml(html);
            }else{
                croPurgoodsVo.setHtml("0");
            }
        }else{
            if(StringUtils.isNotBlank(goods.getDesc())) {
                croPurgoodsVo.setHtml(goods.getDesc());
            }else {
                croPurgoodsVo.setHtml("0");
            }
        }
        return SUCCESS;
    }

    /*
    * 获取商品价格
    * */
    public String getGoodsPrice() {
        //获取商品价格
        System.out.println("getGoodsPriceAction" + goodsid+"数量:"+goodsnumber);
        Double price = 0.0;
        Boolean is = false;
        int j = 0;
        for (int i = 0; i < flag.length; i++) {
            if (StringUtils.isNotBlank(flag[i])) {
                j++;
            }
            System.out.println("flag" + flag[i]);
        }
        for (int i = 0; i < value.length; i++) {
            System.out.println("value" + value[i]);
        }
        System.out.println("j的值:" + j);
        croPurgoodsVo = croPurgoodsService.getUpdateGoodsInfo(goodsid);
        String json = croPurgoodsVo.getDescription();
        CroPurgoodsVos goods = new CroPurgoodsVos();
        goods = JSON.parseObject(json, CroPurgoodsVos.class);
        List<SkusVo> skusVoList = new ArrayList<>();
        skusVoList = goods.getSkus();
        for (SkusVo skusVo : skusVoList) {
            List<GoodsPropertiesNameVo> goodsPropertiesNameVoList = new ArrayList<>();
            goodsPropertiesNameVoList = skusVo.getPropertiesName();
            int k = 0;
            for (GoodsPropertiesNameVo goodsPropertiesNameVo : goodsPropertiesNameVoList) {
                for (int i = 0; i < flag.length; i++) {
                    if (StringUtils.isNotBlank(flag[i])) {
                        if (goodsPropertiesNameVo.getPropName().equals(value[i]) && goodsPropertiesNameVo.getPropValueName().equals(flag[i])) {
                            k++;
                            System.out.println("k值:" + k);
                            break;
                        }
                    }
                }
            }
            if (k == j) {
                if(StringUtils.isNotBlank(goodsnumber)){
                    price = (skusVo.getPrice() + goods.getPrice())*Integer.parseInt(goodsnumber);
                }else {
                    price = skusVo.getPrice() + goods.getPrice();
                }

                is = true;
                break;
            }
        }
        if (is) {
            croPurgoodsVo.setSpecprice(price);
            successResult = price;
        } else {
            croPurgoodsVo.setSpecprice(0.0);
            successResult = 0.0;
        }

        return SUCCESS;
    }

    /*
    * 加入购物车
    * */
    public String addBuycar() {
        System.out.println("addBuycarAction" + goodsid+"总价:"+goodsprice);
        ServletContext context = ServletActionContext.getServletContext();
        CroCustomer croCustomer = (CroCustomer) context.getAttribute("customer");
        if (croCustomer == null) {//用户没登陆
            successResult = 2.0;
            System.out.println("用户没登陆");
        } else if (goodsprice == 0) {//商品价格为0
            successResult = 3.0;
        } else {
            Boolean is = false;
            int j = 0;
            for (int i = 0; i < flag.length; i++) {//得到flag的长度
                if (StringUtils.isNotBlank(flag[i])) {
                    j++;
                }
                System.out.println("flag" + flag[i]);
            }
            List<CroPurchase> croPurchaseList = frontGoodsDetailService.lists(croCustomer.getId());//获取该用户的订单
            CroPurchase croPurchase = new CroPurchase();
            if (croPurchaseList.size() == 0) {//该用户没有订单
                //订单实体
                croPurchase.setCreatedate(new Date());
                croPurchase.setDel_flag("0");
                croPurchase.setExcessfee(20);
                croPurchase.setNotes("测试");
                croPurchase.setOrder_flag("0");
                croPurchase.setOrderStatus("0");
                croPurchase.setPaytype("0");
                croPurchase.setOrderdate(new Date());
                croPurchase.setTotalprice(goodsprice);
                croPurchase.setCroCustomer(croCustomer);
                croPurchase.setOrderType("0");
                //创建购物车实体
                CroBuycars croBuycars = new CroBuycars();
                croBuycars.setActualprice(goodsprice/(Integer.parseInt(goodsnumber)));
                croBuycars.setCreatedate(new Date());
                croBuycars.setCroPurchase(croPurchase);
                croBuycars.setDel_flag("0");
                croBuycars.setNumbers(Integer.parseInt(goodsnumber));
                croBuycars.setSumprice(goodsprice);
                croBuycars.setUpdatedate(new Date());
                //获取商品的描述
                CroPurgoods croPurgoods = croPurgoodsService.getEntityGoods(goodsid);
                croBuycars.setCroPurgoods(croPurgoods);
                String json = croPurgoods.getDescription();
                CroPurgoodsVos goods = new CroPurgoodsVos();
                goods = JSON.parseObject(json, CroPurgoodsVos.class);
                ParseBuycarVo parseBuycarVo = new ParseBuycarVo();
                List<SkusVo> skusVoList = new ArrayList<>();
                skusVoList = goods.getSkus();
                SkusVo tempskusVo = new SkusVo();
                for (SkusVo skusVo : skusVoList) {//找到该商品的信息
                    List<GoodsPropertiesNameVo> goodsPropertiesNameVoList = new ArrayList<>();
                    goodsPropertiesNameVoList = skusVo.getPropertiesName();
                    int k = 0;
                    for (GoodsPropertiesNameVo goodsPropertiesNameVo : goodsPropertiesNameVoList) {
                        for (int i = 0; i < flag.length; i++) {
                            if (StringUtils.isNotBlank(flag[i])) {
                                if (goodsPropertiesNameVo.getPropName().equals(value[i]) && goodsPropertiesNameVo.getPropValueName().equals(flag[i])) {
                                    k++;
                                    System.out.println("k值:" + k);
                                    break;
                                }
                            }
                        }
                    }
                    if (k == j) {
                        tempskusVo = skusVo;
                        break;
                    }
                }
                parseBuycarVo.setPropertiesName(tempskusVo.getPropertiesName());
                parseBuycarVo.setTitle(goods.getTitle());
                System.out.println("title:" + goods.getTitle());
                parseBuycarVo.setCreatedTime(tempskusVo.getCreatedTime());
                parseBuycarVo.setPicUrl(goods.getPicUrl());
                parseBuycarVo.setModifiedTime(tempskusVo.getModifiedTime());
                parseBuycarVo.setQuantity(tempskusVo.getQuantity());
                parseBuycarVo.setUSDPrice(tempskusVo.getPrice());
                parseBuycarVo.setPrice(goodsprice/(Integer.parseInt(goodsnumber)));
                parseBuycarVo.setQuantity(tempskusVo.getQuantity());
                croBuycars.setGoodsdetail(JSON.toJSON(parseBuycarVo).toString());
                if (frontGoodsDetailService.addBuycars(croBuycars, croPurchase)) {
                    successResult = 1.0;
                } else {
                    successResult = 0.0;
                }

            } else {//该用户有订单
                croPurchase = croPurchaseList.get(0);
                Boolean tempflag = false;
                List<CroBuycars> croBuycarsList = frontGoodsDetailService.getPersonBuycars(croPurchase.getId());
                CroBuycars tempCroBuycars = new CroBuycars();
                for (CroBuycars croBuycars : croBuycarsList) {
                    String json = croBuycars.getGoodsdetail();
                    ParseBuycarVo parseBuycarVo = JSON.parseObject(json, ParseBuycarVo.class);
                    List<GoodsPropertiesNameVo> goodsPropertiesNameVoList = parseBuycarVo.getPropertiesName();
                    int k2 = 0;
                    for (GoodsPropertiesNameVo goodsPropertiesNameVo : goodsPropertiesNameVoList) {//找出原购物车是否有该商品
                        for (int i = 0; i < flag.length; i++) {
                            if (StringUtils.isNotBlank(flag[i])) {
                                if (goodsPropertiesNameVo.getPropName().equals(value[i]) && goodsPropertiesNameVo.getPropValueName().equals(flag[i])) {
                                    k2++;
                                    break;
                                }
                            }
                        }
                    }
                    if (k2 == j) {//原购物车有该商品
                        tempCroBuycars = croBuycars;
                        tempflag = true;
                        break;
                    }
                }
                if (tempflag) {//原购物车有该商品后更新购物车
                    tempCroBuycars.setUpdatedate(new Date());
                    tempCroBuycars.setNumbers(tempCroBuycars.getNumbers() + Integer.parseInt(goodsnumber));
                    tempCroBuycars.setSumprice(tempCroBuycars.getSumprice() + goodsprice);
                    //更新操作
                    frontGoodsDetailService.upateBuycars(tempCroBuycars);
                } else {//原购物车无该商品后插入购物车信息
                    //创建购物车实体
                    CroBuycars croBuycars=new CroBuycars();
                    croBuycars.setActualprice(goodsprice/(Integer.parseInt(goodsnumber)));
                    croBuycars.setCreatedate(new Date());
                    croBuycars.setCroPurchase(croPurchaseList.get(0));
                    croBuycars.setDel_flag("0");
                    croBuycars.setNumbers(Integer.parseInt(goodsnumber));
                    croBuycars.setSumprice(goodsprice);
                    croBuycars.setUpdatedate(new Date());
                    CroPurgoods croPurgoods = croPurgoodsService.getEntityGoods(goodsid);
                    croBuycars.setCroPurgoods(croPurgoods);
                    String json = croPurgoods.getDescription();
                    CroPurgoodsVos goods = new CroPurgoodsVos();
                    goods = JSON.parseObject(json, CroPurgoodsVos.class);
                    ParseBuycarVo parseBuycarVo = new ParseBuycarVo();
                    List<SkusVo> skusVoList = new ArrayList<>();
                    skusVoList = goods.getSkus();
                    SkusVo tempskusVo = new SkusVo();
                    for (SkusVo skusVo : skusVoList) {
                        List<GoodsPropertiesNameVo> goodsPropertiesNameVoList = new ArrayList<>();
                        goodsPropertiesNameVoList = skusVo.getPropertiesName();
                        int k = 0;
                        for (GoodsPropertiesNameVo goodsPropertiesNameVo : goodsPropertiesNameVoList) {
                            for (int i = 0; i < flag.length; i++) {
                                if (StringUtils.isNotBlank(flag[i])) {
                                    if (goodsPropertiesNameVo.getPropName().equals(value[i]) && goodsPropertiesNameVo.getPropValueName().equals(flag[i])) {
                                        k++;
                                        System.out.println("k值:" + k);
                                        break;
                                    }
                                }
                            }
                        }
                        if (k == j) {
                            tempskusVo = skusVo;
                            break;
                        }
                    }
                    parseBuycarVo.setPropertiesName(tempskusVo.getPropertiesName());
                    parseBuycarVo.setTitle(goods.getTitle());
                    System.out.println("title:" + goods.getTitle());
                    parseBuycarVo.setCreatedTime(tempskusVo.getCreatedTime());
                    parseBuycarVo.setPicUrl(goods.getPicUrl());
                    parseBuycarVo.setModifiedTime(tempskusVo.getModifiedTime());
                    parseBuycarVo.setQuantity(tempskusVo.getQuantity());
                    parseBuycarVo.setUSDPrice(tempskusVo.getPrice());
                    parseBuycarVo.setPrice(goodsprice/(Integer.parseInt(goodsnumber)));
                    parseBuycarVo.setQuantity(tempskusVo.getQuantity());
                    croBuycars.setGoodsdetail(JSON.toJSON(parseBuycarVo).toString());
                    if (frontGoodsDetailService.addBuycars(croBuycars, null)) {
                        successResult = 1.0;
                    } else {
                        successResult = 0.0;
                    }

                }

            }
        }
        return SUCCESS;
    }
    /*
    * 获取url的html
    * */
    @SuppressWarnings("resource")
    public static String getHtmlByURL(String myURL) {
        URL url = null;
        String htmlContext = "";
        try {
            url = new URL(myURL);
            HttpURLConnection conn;
            try {
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestProperty("User-Agent", // 很重要
                        "Mozilla/5.0 (X11; U; Linux i686; zh-CN; rv:1.9.1.2)"
                                + "Gecko/20090803 Fedora/3.5.2-2.fc11 Firefox/3.5.2");
                conn.setRequestMethod("GET");
                Scanner scanner = new Scanner(conn.getInputStream());
                while (scanner.hasNextLine()) {
                    htmlContext += scanner.nextLine();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return htmlContext;
    }


    public CroPurgoodsVo getCroPurgoodsVo() {
        return croPurgoodsVo;
    }

    public void setCroPurgoodsVo(CroPurgoodsVo croPurgoodsVo) {
        this.croPurgoodsVo = croPurgoodsVo;
    }

    public String getGoodsid() {
        return goodsid;
    }

    public void setGoodsid(String goodsid) {
        this.goodsid = goodsid;
    }

    public String[] getValue() {
        return value;
    }

    public void setValue(String[] value) {
        this.value = value;
    }

    public String[] getFlag() {
        return flag;
    }

    public void setFlag(String[] flag) {
        this.flag = flag;
    }

    public Double getSuccessResult() {
        return successResult;
    }

    public void setSuccessResult(Double successResult) {
        this.successResult = successResult;
    }

    public List<CroPurgoodsVo> getCroPurgoodsVoList() {
        return croPurgoodsVoList;
    }

    public void setCroPurgoodsVoList(List<CroPurgoodsVo> croPurgoodsVoList) {
        this.croPurgoodsVoList = croPurgoodsVoList;
    }

    public Double getGoodsprice() {
        return goodsprice;
    }

    public void setGoodsprice(Double goodsprice) {
        this.goodsprice = goodsprice;
    }

    public String getGoodsnumber() {
        return goodsnumber;
    }

    public void setGoodsnumber(String goodsnumber) {
        this.goodsnumber = goodsnumber;
    }

}
